package com.zy.explore.core;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * description 生成 {@link ObjectId} 的默认工厂
 *
 * @author ZY
 * @date 2021-05-05 18:03
 */
final class CustomObjectIdFactory implements ObjectIdFactory {

    private static final int THREE_BYTES_MASK = 0xffffff;

    private final int machineId;

    private final short processId;

    private final AtomicInteger idCounter;

    CustomObjectIdFactory(int machineId, short processId, int idCounter) {
        this.machineId = machineId;
        this.processId = processId;
        this.idCounter = new AtomicInteger(idCounter);
    }

    @Override
    public ObjectId generate() {
        int timestamp = (int) (System.currentTimeMillis() / 1000L);
        int counter = idCounter.getAndIncrement() & THREE_BYTES_MASK;

        return new ObjectId(timestamp, machineId, processId, counter);
    }
}
